<template>
  <div class="chat-section-container">
    <!-- 消息显示区域 -->
    <div class="messages-container">
      <ChatMessages :messages="messages" :currentUser="currentUser" :pinID="pinId"/>
    </div>

    <!-- 输入框区域 -->
    <div class="input-container">
      <ChatInput 
	  :pinID="pinId"
	  :userID="currentUser"
	  @sendMessage="handleSendMessage" />
    </div>
  </div>
</template>

<script>
import ChatInput from "./ChatInput.vue";
import ChatMessages from "./ChatMessages.vue";
import { ChatAPI, UserAPI } from "../../services/api";  // 引入 ChatAPI

export default {
  name: "ChatSection",
  components: {
    ChatInput,
    ChatMessages,
  },
  props: {
    currentUser: {
      type: Number,
      required: true,
    },
    pinId: {
      type: Number,
      required: true,
    },
	pinInfo: {
		type: Object,
		required: false,
	}
  },
  data() {
    return {
      messages: [],  // 存储聊天记录
      pollingInterval: null,  // 定时器ID，用于清除定时器
      userCache: {},  // 用户信息缓存
    };
  },
  mounted() {
    this.fetchChats();
    // 在组件加载时，启动定时器每秒调用一次 fetchChats 方法
    this.startPolling();
  },
  beforeDestroy() {
    // 在组件销毁时清理定时器，避免内存泄漏
    if (this.pollingInterval) {
      clearInterval(this.pollingInterval);
    }
  },
  methods: {
    async fetchChats() {
      try {
        const response = await ChatAPI.getChatsByPin(this.pinId);
        
        const users = [];
        for (const chat of response) {
          const userInfo = await this.getUserInfo(chat.userID);  // 获取每个用户的信息
          users.push(userInfo);
        }

        // 将用户信息和消息内容一起处理
        this.messages = response.map((chat, index) => ({
          id: chat.messageID,            // 消息ID
          sender: users[index].userID,   // 获取发送者的用户名
          senderName: users[index].username,
          text: chat.messageContent,     // 消息内容
          time: chat.messageTime,        // 消息时间
          avatar: this.getUserAvatar(chat.userID), // 获取发送者头像
        }));
        
        console.log(this.messages); // 输出消息列表
      } catch (error) {
        console.error("Failed to fetch chats:", error);
      }
    },

    // 获取用户信息并缓存
    async getUserInfo(userID) {
      // 如果缓存中已有用户信息，则直接返回
      if (this.userCache[userID]) {
        return this.userCache[userID];
      }
      
      try {
        const userResponse = await UserAPI.getUserById(userID);
        // 将用户信息缓存到 userCache 中
        this.userCache[userID] = userResponse;
        return userResponse;
      } catch (error) {
        console.error(`Failed to fetch user info for ${userID}:`, error);
        return {};  // 如果请求失败，返回一个空对象
      }
    },

    getUserAvatar(userID) {
      return `https://cdn.builder.io/api/v1/image/assets/TEMP/5e120dc80a685f9ec0da710923e601b97b21db93a5cc47b1cea7902427bc56fd?placeholderIfAbsent=true&apiKey=933e78dc5ac54c44868b43c2dcd912d5`;
    },

    startPolling() {
      // 每隔一秒调用一次 fetchChats
      this.pollingInterval = setInterval(() => {
        this.fetchChats();
      }, 1500);  // 每1000ms (1秒) 调用一次
    },

    handleSendMessage(message) {
      // 发送消息时，更新本地聊天记录
      this.messages.push({
        sender: this.currentUser,
        text: message,
        avatar: this.getUserAvatar(this.currentUser), // 根据当前用户ID获取头像
        time: new Date().toISOString(), // 获取当前时间
      });

      // 调用 API 创建新的聊天记录（可选）
      console.log(this.pinId, this.currentUser);
      const chatData = {
        pinID: this.pinId,
        userID: this.currentUser, // 当前用户ID，需要动态获取
        messageContent: message,
      };
      ChatAPI.createChat(chatData)
        .then((response) => {
          console.log("Message sent successfully:", response);
        })
        .catch((error) => {
          console.error("Failed to send message:", error);
        });
    },
  },
};
</script>





<style scoped>
.chat-section-container {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  height: 75vh;
  border: 1px solid #ddd;
  border-radius: 5px;
  background-color: #fff;
  overflow: hidden;
  border-bottom: none; /* 去掉底部边框 */
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 0px;
  background-color: #f9f9f9;
}

.input-container {
  flex-shrink: 0; /* 防止输入框被压缩 */
  border-top: 1px solid #ddd;
  background-color: #fff;
}
</style>
